package com.wbao.dianniu.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.OptionsPickerView.OnOptionsSelectListener;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.adapter.WorkExperienceAdapter;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.MyListView;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.customView.PickerView;
import com.wbao.dianniu.customView.PickerView.onSelectListener;
import com.wbao.dianniu.data.ChildZone;
import com.wbao.dianniu.data.JobDetailData;
import com.wbao.dianniu.data.WorkExperienceData;
import com.wbao.dianniu.data.Zone;
import com.wbao.dianniu.listener.IJobDetailListener;
import com.wbao.dianniu.listener.IJobReleaseListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.JobDetailManager;
import com.wbao.dianniu.manager.JobReleaseManager;
import com.wbao.dianniu.manager.WorkListChangeManager;
import com.wbao.dianniu.manager.WorkListChangeManager.WorkChangedListener;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 简历编辑
 * 
 * @author yejianjun
 * 
 */
public class JobEditActivity extends BaseActivity implements IJobReleaseListener,WorkChangedListener,IJobDetailListener {
	/** 省数据 */
	private ArrayList<String> provinceList = new ArrayList<>();
	/** 市数据 */
	private ArrayList<ArrayList<String>> cityList = new ArrayList<>();
	private OptionsPickerView pvOptions;
	//弹出选择对话框
	private Dialog dialog;
	private String strMoney="";
	private String strYears="";
	private String strXueli="";
	private JobReleaseManager manager;
	private ImageView iv_head;
	private TextView userName;
	private TextView userLabel;
	private EditText tv_subject;
	private TextView tvSalary;
	private TextView tv_address;
	private TextView tvExperience;
	private TextView tvEducation;
//	private TextView tvTryout;
	private Button releaseBtn;
	private Dialog pDialog;
//	private String[] tryoutList = new String[]{"可试用","不可试用"};
	private Button editJobExperience;
	private Button addJobExperience;
	private MyListView mListView;
	private JobDetailManager detailManger;
	private String headPic = "";
	private WorkExperienceAdapter adapter;
	private List<WorkExperienceData> experienceList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentLayout(R.layout.activity_job_edit,LayoutParams.MATCH_PARENT,android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
		setTitleName(getResources().getString(R.string.edit_resume));
		ImageButton backButton = getBackView();
		backButton.setImageResource(R.drawable.cancel_res_icon);
		Button fbBtn = getRightTextButton();
		fbBtn.setText(getResources().getString(R.string.preview));
		fbBtn.setOnClickListener(this);
		init();
		initManger();
		initData();
	}
	private void initData(){
		experienceList = new ArrayList<WorkExperienceData>();
		adapter = new WorkExperienceAdapter(this,1);
		adapter.setData(experienceList);
		mListView.setAdapter(adapter);
		setListViewHeightBasedOnChildren(mListView);
	}
	private void init(){
		RelativeLayout rl_money = (RelativeLayout) findViewById(R.id.relative_money);
		RelativeLayout rl_workArea = (RelativeLayout) findViewById(R.id.relative_work_area);
		RelativeLayout rl_wrok_years = (RelativeLayout) findViewById(R.id.relative_work_years);
		RelativeLayout rl_xueli = (RelativeLayout) findViewById(R.id.relative_xueli);
		mListView = (MyListView) findViewById(R.id.work_experience_list);
		editJobExperience = (Button) findViewById(R.id.job_edit_button);
		addJobExperience = (Button) findViewById(R.id.add_job_experience);
		iv_head = (ImageView) findViewById(R.id.user_head);
		userName = (TextView) findViewById(R.id.user_name);
		userLabel = (TextView) findViewById(R.id.user_label);
		tv_subject = (EditText) findViewById(R.id.applay_job_name);
		tv_address = (TextView) findViewById(R.id.job_area_tv);
		releaseBtn = (Button) findViewById(R.id.job_release_button);
		rl_money.setOnClickListener(this);
		rl_workArea.setOnClickListener(this);
		rl_wrok_years.setOnClickListener(this);
		rl_xueli.setOnClickListener(this);
		releaseBtn.setOnClickListener(new NoDoubleClickListener() {
			
			@Override
			public void onNoDoubleClick(View v) {
				applay();
			}
		});
		editJobExperience.setOnClickListener(this);
		addJobExperience.setOnClickListener(this);
		mListView.setClickable(false);
		tvSalary = (TextView) findViewById(R.id.money_content_tv);
		tvExperience = (TextView) findViewById(R.id.job_years_tv);
		tvEducation = (TextView) findViewById(R.id.xueli_tv);
	}
	
	private void initManger() {
		manager = new JobReleaseManager(this);
		manager.addJobReleaseListener(this);
		detailManger = new JobDetailManager(this);
		detailManger.addJobDetailListener(this);
		detailManger.jobDetail(GlobalContext.accountId, GlobalContext.accountId);
		WorkListChangeManager.getInstance().addWorkChangeListener(this);
	}
	
	private View showRealase(int layoutId){
		dialog = new Dialog(this, R.style.custom_Dialog);
		Window win = dialog.getWindow();
		win.getDecorView().setPadding(0, 0, 0, 0);
		win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
		WindowManager.LayoutParams lp = win.getAttributes();
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		win.setAttributes(lp);
		win.setWindowAnimations(R.style.buttom_animation);
		View view = LayoutInflater.from(this).inflate(layoutId,null);
		dialog.setContentView(view);
		dialog.setCancelable(true);
		dialog.show();
		return view;
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.relative_money:	//期望薪资
			// 隐藏键盘
			Utils.hideSoftInput(JobEditActivity.this, tv_subject);
			
			View viewMoney = showRealase(R.layout.job_release_money);
			PickerView pickerMoney = (PickerView) viewMoney.findViewById(R.id.picker_money);
			List<String> datas = new ArrayList<String>();
			String[] xinziStr = getResources().getStringArray(R.array.salary_array);
			for (int i = 0; i < xinziStr.length; i++) {
				datas.add(xinziStr[i]);
			}
			pickerMoney.setData(datas);
			if ("".equals(strMoney)) {
				strMoney = xinziStr[0];
			}
			pickerMoney.setOnSelectListener(new onSelectListener() {
				
				@Override
				public void onSelect(String text) {
					// TODO Auto-generated method stub
					strMoney = text;
				}
			});
			Button confirmMoney = (Button) viewMoney.findViewById(R.id.job_money_confirm);
			confirmMoney.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					tvSalary.setText(strMoney);
					if(null != dialog && dialog.isShowing()){
						dialog.dismiss();
					}
				}
			});
			break;
		case R.id.relative_work_area:	//工作地区
			// 隐藏键盘
			Utils.hideSoftInput(JobEditActivity.this, tv_subject);
			
			initAreaData();
			break;
		case R.id.relative_work_years:		//工作经验
			// 隐藏键盘
			Utils.hideSoftInput(JobEditActivity.this, tv_subject);
			
			View viewYear = showRealase(R.layout.job_release_money);
			PickerView pickerYear = (PickerView) viewYear.findViewById(R.id.picker_money);
			List<String> datasYear = new ArrayList<String>();
			String[] experience = getResources().getStringArray(R.array.job_experience_array);
			for (int i = 0; i < experience.length; i++) {
				datasYear.add(experience[i]);
			}
			pickerYear.setData(datasYear);
			if ("".equals(strYears)) {
				strYears = experience[0];
			}
			pickerYear.setOnSelectListener(new onSelectListener() {
				
				@Override
				public void onSelect(String text) {
					// TODO Auto-generated method stub
					strYears = text;
				}
			});
			Button confirmYear = (Button) viewYear.findViewById(R.id.job_money_confirm);
			confirmYear.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					tvExperience.setText(strYears);
					if(null != dialog && dialog.isShowing()){
						dialog.dismiss();
					}
				}
			});
			break;
		case R.id.relative_xueli:	//学历
			// 隐藏键盘
			Utils.hideSoftInput(JobEditActivity.this, tv_subject);
			
			View viewXueli = showRealase(R.layout.job_release_money);
			PickerView pickerXueli = (PickerView) viewXueli.findViewById(R.id.picker_money);
			List<String> datasXueli = new ArrayList<String>();
			String[] education = getResources().getStringArray(R.array.education_no_unlimited);
			for (int i = 0; i < education.length; i++) {
				datasXueli.add(education[i]);
			}
			pickerXueli.setData(datasXueli);
			if("".equals(strXueli)){
				strXueli = education[0];
			}
			pickerXueli.setOnSelectListener(new onSelectListener() {
				
				@Override
				public void onSelect(String text) {
					strXueli = text;
				}
			});
			Button confirmXueli = (Button) viewXueli.findViewById(R.id.job_money_confirm);
			confirmXueli.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					tvEducation.setText(strXueli);
					if(null != dialog && dialog.isShowing()){
						dialog.dismiss();
					}
				}
			});
			break;
		case R.id.right_button:	//预览
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString(GlobalContext.BUNDLE_HEADPIC, headPic );
			bundle.putString(GlobalContext.BUNDLE_REALNAME, userName.getText().toString().trim());
			bundle.putString(GlobalContext.BUNDLE_LABEL, userLabel.getText().toString().trim());
			bundle.putString(GlobalContext.BUNDLE_SUBJECT,tv_subject.getText().toString().trim() );
//			bundle.putString(GlobalContext.BUNDLE_TRYOUT, tvTryout.getText().toString().trim());
			bundle.putString(GlobalContext.BUNDLE_SALARY, tvSalary.getText().toString().trim());
			bundle.putString(GlobalContext.BUNDLE_ADDRESS, tv_address.getText().toString().trim());
			bundle.putString(GlobalContext.BUNDLE_EXPERIENCE, tvExperience.getText().toString().trim());
			bundle.putString(GlobalContext.BUNDLE_EDUCATION, tvEducation.getText().toString().trim());
			bundle.putString(GlobalContext.BUNDLE_CONTENT, Utils.WorkListDataToString(experienceList));
			intent.putExtra(GlobalContext.BUNDLE_DATA, bundle);
			intent.setClass(JobEditActivity.this, JobPreviewActivity.class);
			startActivity(intent);
			break;
		case R.id.job_edit_button:// 编辑工作经历
			Intent edit = new Intent();
			edit.setClass(JobEditActivity.this, EditJobExActivity.class);
			startActivity(edit);
			break;
		case R.id.add_job_experience:	// 添加工作经历
			Intent add = new Intent();
			add.setClass(JobEditActivity.this, AddJobExActivity.class);
			startActivity(add);
			break;
//		case R.id.job_release_button:// 发布
//			applay();
//			break;
		default:
			break;
		}

	}

	@Override
	public void onJobReleaseFailure(int errorCode, String errorMsg) {
		if(null != pDialog && pDialog.isShowing()){
			pDialog.dismiss();
		}
		Notification.toast(this, errorMsg);
	}

	@Override
	public void onJobReleaseSuccess() {
		if(null != pDialog && pDialog.isShowing()){
			pDialog.dismiss();
		}
		Notification.toast(this, "发布成功" );
		/**	修改简历完善状态 改成已完善	*/ 
		GlobalContext.isPerfectResume = true;
		finish();
	}
	
	/**
	 * 地区选择器
	 */
	private void initAreaData(){
		//选项选择器
	    pvOptions = new OptionsPickerView(this);
		InputStream input = getResources().openRawResource(R.raw.zone);
		String jsonData = Utils.inputStream2String(input, "utf-8");
		List<Zone> zoneList = (List<Zone>) JsonUtil.toObjectList(jsonData, Zone.class);
		for (Iterator iterator = zoneList.iterator(); iterator.hasNext();) {
			Zone zone = (Zone) iterator.next();
			provinceList.add(zone.getName());
			LinkedList<ChildZone> linkList = zone.getChildrens();
			ArrayList<String> arrayList = new ArrayList<String>();
			for (int i = 0; i < linkList.size(); i++) {
				arrayList.add(linkList.get(i).getName());
			}
			cityList.add(arrayList);
		}
		
	    pvOptions.setPicker(provinceList, cityList, true);
        pvOptions.setTitle(getResources().getString(R.string.city_selected));
        pvOptions.setCyclic(false);
		
        pvOptions.setSelectOptions(1, 1);
        pvOptions.setOnoptionsSelectListener(new OnOptionsSelectListener() {

			@Override
			public void onOptionsSelect(int options1, int option2, int options3) {
				String areaStr = provinceList.get(options1) + cityList.get(options1).get(option2);
				tv_address.setText(areaStr);
			}
		});
        pvOptions.show();
	}
	
	private void applay(){
		if(TextUtils.isEmpty(tv_subject.getText().toString())){
			Notification.toast(this, "选择应聘岗位");
			tv_subject.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tvSalary.getText().toString())){
			Notification.toast(this, "选择薪资");
			tvSalary.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tv_address.getText().toString())){
			Notification.toast(this, "选择工作地区");
			tv_address.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tvExperience.getText().toString())){
			Notification.toast(this, "选择工作经验");
			tvExperience.requestFocus();
			return;
		}else if(TextUtils.isEmpty(tvEducation.getText().toString())){
			Notification.toast(this, "选择学历");
			tvEducation.requestFocus();
			return;
		}
		/*if(TextUtils.isEmpty(tvTryout.getText().toString())){
			Notification.toast(this, "选择是否可试用");
			tvTryout.requestFocus();
			return;
		}*/
		pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
		pDialog.show();
		manager.jobRelease(GlobalContext.accountId, tv_subject.getText().toString().trim(), tvSalary.getText().toString().trim(), tvExperience.getText().toString().trim(), tvEducation.getText().toString().trim(), tv_address.getText().toString().trim());
	}
	
	@Override
	public void workAddChanged(WorkExperienceData data) {
		experienceList.add(data);
//		adapter.setData(experienceList);
		setListViewHeightBasedOnChildren(mListView);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void workRemoveChanged(int position) {
		experienceList.remove(position);
//		adapter.setData(experienceList);
		setListViewHeightBasedOnChildren(mListView);
		adapter.notifyDataSetChanged();
	};

	@Override
	public void onJobDetailFailure(int errorCode, String errorMsg) {
		
	}

	@Override
	public void onJobDetailSuccess(JobDetailData data) {
		if(null != data){
			display(data);
		}
	}
	private void display(JobDetailData data){
		if(!TextUtils.isEmpty(data.getHeadPic())){
			headPic = data.getHeadPic();
			PictureDownloadUtils.displayHeadImage(this,iv_head, data.getHeadPic());
		}
		userName.setText(data.getRealName() == null ? "": data.getRealName());
		userLabel.setText(data.getLabel() == null ? "": data.getLabel());
		if(!TextUtils.isEmpty(data.getPost())){
			tv_subject.setText(data.getPost());
		}
		if(!TextUtils.isEmpty(data.getSalary())){
			tvSalary.setText(data.getSalary());
		}
		if(!TextUtils.isEmpty(data.getAddress())){
			tv_address.setText(data.getAddress());
		}
		if(!TextUtils.isEmpty(data.getExperience())){
			tvExperience.setText(data.getExperience());
		}
		if(!TextUtils.isEmpty(data.getEducation())){
			tvEducation.setText(data.getEducation());
		}
		if (!TextUtils.isEmpty(data.getDescribe())) {
			experienceList = Utils.parseWorkData(data.getDescribe());
			adapter.setData(experienceList);
			setListViewHeightBasedOnChildren(mListView);
			adapter.notifyDataSetChanged();
		}
	}
	
	public void setListViewHeightBasedOnChildren(ListView listView) {   
        // 获取ListView对应的Adapter   
        int totalHeight = 0;   
        for (int i = 0, len = adapter.getCount(); i < len; i++) {   
            // listAdapter.getCount()返回数据项的数目   
            View listItem = adapter.getView(i, null, listView);   
            // 计算子项View 的宽高   
            listItem.measure(0, 0);    
            // 统计所有子项的总高度   
            totalHeight += listItem.getMeasuredHeight();    
        }   
   
        ViewGroup.LayoutParams params = listView.getLayoutParams();   
        params.height = totalHeight+ (listView.getDividerHeight() * (adapter.getCount() - 1));   
        // listView.getDividerHeight()获取子项间分隔符占用的高度   
        // params.height最后得到整个ListView完整显示需要的高度   
        listView.setLayoutParams(params);   
    }
	@Override
	public void workModifyChanged(int id, WorkExperienceData data) {
		for (int i = 0; i < experienceList.size(); i++) {
			if(id == experienceList.get(i).getId()){
				experienceList.get(i).setPost(data.getPost());
				experienceList.get(i).setStartDate(data.getStartDate());
				experienceList.get(i).setEndDate(data.getEndDate());
				experienceList.get(i).setContent(data.getContent());
				break;
			}
		}
//		adapter.setData(experienceList);
		setListViewHeightBasedOnChildren(mListView);
		adapter.notifyDataSetChanged();
	}   
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		}
		public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		}
		@Override
		protected void onDestroy() {
			super.onDestroy();
			if(null != pDialog && pDialog.isShowing()){
				pDialog.dismiss();
			}
		}
}
